import CommonUtil from "../utils/CommonUtil";
import Wx, {wx} from "./Wx";

export default class AdsProvider {

    private adUnitId: string = "";

    private banner: any = null;
    private bannerCreateTime: number = 0;
    // 最小广告创建间隔. 为负值表示每次都创建.
    private minCreateTimeSpan: number = 60 * 1000;

    // 广告条宽度,比例. 0-1. 表示屏幕多宽的尺寸
    private adsWidth: number = 0.8;

    private isShowing: boolean = false;

    private alignTop: boolean = false;

    /**
     * banner 更换频率.设置越高,可能越消耗用户流量.
     * @param {number} span
     */
    public setMinCreateSpan(span: number) {
        this.minCreateTimeSpan = span < 0 ? 0 : span;
    }

    public setAlignTop(top: boolean) {
        this.alignTop = top;
    }

    public setAdUnitId(id: string) {
        this.adUnitId = id;
    }

    /**
     * 设置banner 所占宽度.最小为300px.
     * @param {number} width
     */
    public setAdsWidth(width: number) {
        this.adsWidth = width < 0 ? 0.5 : (width > 1 ? 1 : width);
    }

    /**
     * 展现广告banner. 可以设定一个延时展现的时长.为0立即展现.
     * @param {number} delaySeconds
     * @returns {Promise<>}
     */
    public async showAds(delaySeconds: number = 0) {

        if (!Wx.isWeChatEnv()) {
            console.error("非微信环境,不能添加广告");
            return;
        }
        if (this.isShowing) {
            console.warn("广告已展现,不能重复展现.");
            return;
        }
        this.isShowing = true;

        if (this.banner == null) {
            await this.createAds();
        } else if (Date.now() - this.bannerCreateTime > this.minCreateTimeSpan) {
            // 时间 超过3分钟,重新换个广告.
            await this.createAds();
        }

        if (this.banner) {
            if (delaySeconds > 0) {
                await CommonUtil.delay(delaySeconds);
            }
            return this.banner.show();
        } else {
            return Promise.reject("banner 为空.");
        }
    }

    /**
     * 隐藏banner.
     */
    public hideAds() {
        if (this.isShowing == false) {
            console.warn("广告未展现,不能隐藏.");
            return;
        }
        this.isShowing = false;
        if (this.banner) {
            this.banner.hide();
        }
    }

    private createAds(): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            if (Wx.isWeChatEnv()) {
                cc.log("创建新的广告内容.");
                this.bannerCreateTime = Date.now();
                if (this.banner) {
                    this.banner.destroy();
                    this.banner = null;
                }
                const sysInfo = wx.getSystemInfoSync();
                cc.log("系统信息:", sysInfo);
                if (sysInfo.SDKVersion < "2.0.4") {
                    console.warn("基础库版本<2.0.4, 无法显示广告.");
                    resolve(null);
                    return;
                }

                this.banner = wx.createBannerAd({
                    adUnitId: this.adUnitId,
                    style: {
                        left: 0,
                        top: -500,
                        width: Math.ceil(sysInfo.screenWidth * this.adsWidth).toFixed(0),
                    },
                });
                this.banner.onResize((size) => {
                    let adjust = this.alignTop ? 0 : (Wx.isIPX() ? 10 : 0);
                    cc.log("当前系统是否是IPX:", Wx.isIPX(), adjust);
                    this.banner.style.top = this.alignTop ? 0 : sysInfo.screenHeight - size.height - adjust;
                    this.banner.style.left = Math.floor((sysInfo.screenWidth - this.banner.style.realWidth) / 2).toFixed(0);
                    cc.log("广告位尺寸:", this.banner.style.left, this.banner.style.top, this.banner.style.realWidth, this.banner.style.realHeight);
                    resolve(this.banner);
                });
                this.banner.onError((err) => {
                    cc.log("广告位异常:", err);
                    reject();
                });
            }
        });
    }
}

export const bannerAds: AdsProvider = new AdsProvider();